﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ebc.viz.contracts;
using Microsoft.Msagl.Drawing;

namespace ebc.viz.frontend
{
    public partial class WinViewer : Form, IFrontend
    {
        private Graph[] _graphs;
        private Node _selectedNode;

        private Stack<int> _indexHistory = new Stack<int>();
        private Stack<int> _indexFuture = new Stack<int>();


        public WinViewer()
        {
            InitializeComponent();
        }


        public void DisplayGraphs(Graph[] graphs)
        {
            _graphs = graphs;

            this.cboGraphs.Items.Clear();
            this.cboGraphs.Items.AddRange(graphs.Select(g => g.Label.Text).ToArray());

            if (graphs.Length > 0)
                this.cboGraphs.SelectedIndex = 0;
        }


        private void cboGraphs_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.graphViewer.Graph = _graphs[this.cboGraphs.SelectedIndex];
        }


        private void graphViewer_SelectionChanged(object sender, EventArgs e)
        {
            _selectedNode = this.graphViewer.SelectedObject as Node;
        }

        private void graphViewer_DoubleClick(object sender, EventArgs e)
        {
            if (_selectedNode == null) return;

            for(var i=0; i<_graphs.Length; i++)
            {
                if (_graphs[i].Label.Text.StartsWith(_selectedNode.LabelText))
                {
                    _indexHistory.Push(this.cboGraphs.SelectedIndex);
                    this.btnBack.Enabled = true;
                    this.cboGraphs.SelectedIndex = i;
                    return;
                }
            }
        }


        private void btnBack_Click(object sender, EventArgs e)
        {
            _indexFuture.Push(this.cboGraphs.SelectedIndex);
            btnFwd.Enabled = true;

            this.cboGraphs.SelectedIndex = _indexHistory.Pop();
            btnBack.Enabled = _indexHistory.Count > 0;
        }


        private void btnFwd_Click(object sender, EventArgs e)
        {
            _indexHistory.Push(this.cboGraphs.SelectedIndex);
            this.btnBack.Enabled = true;

            this.cboGraphs.SelectedIndex = _indexFuture.Pop();
            btnFwd.Enabled = _indexFuture.Count > 0;
        }
    }
}
